package com.beiding.config;

import org.springframework.data.solr.core.query.result.HighlightEntry;
import org.springframework.data.solr.core.query.result.HighlightPage;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public final class HighlightMapper {

    private Map<String, Field> fieldMap = new HashMap<>();

    //将结果高亮字段合并到对象
    public <T> void map(HighlightPage<T> page) {
        page.forEach(v -> {
            List<HighlightEntry.Highlight> highlights = page.getHighlights(v);
            highlights.forEach(highlight -> {
                String fName = highlight.getField().getName();


                String tf = v.getClass().getName() + fName;

                Field f = fieldMap.get(tf);

                if (f == null) {
                    try {
                        f = v.getClass().getDeclaredField(fName);
                        f.setAccessible(true);
                        Class<?> type = f.getType();
                        if (type == String.class) {
                            fieldMap.put(tf, f);
                        } else {
                            throw new RuntimeException("只支持String类型高亮");
                        }
                    } catch (NoSuchFieldException e) {
                        throw new RuntimeException(e);
                    }
                }

                try {
                    f.set(v, highlight.getSnipplets().get(0));
                } catch (IllegalAccessException ignore) {

                }

            });
        });
    }

}
